<template>
  <div style="width: 100%; height: 100%">


    <Descriptions size="small" :title="totalTitle" v-if="totalObj?.salesmanDeptList.length > 1"
      style="margin-top: 10px;">
      <DescriptionsItem label="选择审批通过收款日期">
        <MonthPicker placeholder="请选择月份" @change="monthChangeFn" format="YYYY-MM"></MonthPicker>
      </DescriptionsItem>
      <DescriptionsItem label="收款抽成汇总">{{ totalObj.orderCommissionPrice }}{{ totalObj.orderCommissionPrice ? '元' : '' }}
      </DescriptionsItem>
      <DescriptionsItem label="接单人抽汇总">{{ totalObj.receiverUserPrice }}{{ totalObj.receiverUserPrice ? '元' : '' }}
      </DescriptionsItem>
      <DescriptionsItem label="跟单人抽汇总">{{ totalObj.merchandiserUserPrice }}{{ totalObj.merchandiserUserPrice ? '元' : ''
      }}
      </DescriptionsItem>
      <DescriptionsItem label="经理抽成汇总"> {{ totalObj.manageUserName ? totalObj.manageUserName + ":" : "" }} {{
        totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</DescriptionsItem>
      <DescriptionsItem label="团建基金抽成汇总"> {{ totalObj.manageUserName ? totalObj.manageUserName + ":" : "" }} {{
        totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</DescriptionsItem>
      <DescriptionsItem label="项目组抽成汇总"> {{ totalObj.xiangMuGroupName ? totalObj.xiangMuGroupName + ":" : "" }} {{
        totalObj.xiangMuGroupPrice }}{{ totalObj.xiangMuGroupPrice ? '元' : '' }}</DescriptionsItem>


    </Descriptions>

    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>

      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>
      <template #state="{ row }">
        <Tag :color="paseTags(row).color">{{ paseTags(row).val }}</Tag>
      </template>

    </vxe-grid>


    <FormModal @register="register" @success="handleSuccess" />

    <Modal v-model:visible="applyViewShow" title="审批详情" @ok="applyViewClose">
      <div>
        <div style="margin-bottom: 5px;">审批详情:</div>
        <Timeline>
          <TimelineItem v-for="(item, index) in applyHistoryList" :key="index" :color="item.color">
            <!-- <template #dot><clock-circle-outlined v-if="!item.endTime" style="font-size: 16px" /></template> -->

            <div style="display: flex;">
              <div>{{ item.nodeName }}</div>
              <div style="margin-left: 20px;">
                <div v-for="(item2, index2) in item.actions" style="cursor: pointer;">
                  <div>
                    <span>{{ item2.userName }}</span> <span>{{ item2.actionName }}</span> <span>{{ item2.finishTime
                      }}</span>
                  </div>
                </div>
                <div v-for="(item2, index2) in item.commentList"
                  style=" border-radius: 8px;background: #ebe9e9;font-size: 12px;cursor: pointer;">
                  <div style="padding: 10px;">
                    <div>
                      <span>{{ item2.comment }}</span> <span>{{ item2.commentTime }}</span>

                    </div>
                    <div v-for="(item3, index3) in item2.picAttachmentList">
                      图片({{ item3.fileName }})前往薪福通查看
                      <img :src="item3.picUrl" style="width: 10px;height: 10px" />
                    </div>
                  </div>

                </div>

              </div>
            </div>

          </TimelineItem>
        </Timeline>
      </div>
    </Modal>

  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  ywApproveList, approveBack, approvalHistory, xftList, syncMoneyTable, approveAbolish, getCountDeptTotalLog
} from '@/api/heng/ywManage';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns,
  vxeTableFormSchema,
} from './role.data';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { Tag, Descriptions, DescriptionsItem } from 'ant-design-vue';
import { reactive, ref, unref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import FormModal from './FormModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button, Timeline, TimelineItem, MonthPicker } from 'ant-design-vue';
import { ClockCircleOutlined } from '@ant-design/icons-vue';

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

const [register, { openModal, closeModal }] = useModal();
const orderModal = useModal();
const loading = ref(false);
const visible = ref(false);
const applyViewShow = ref(false);

const totalObj = ref({ salesmanDeptList: [] })
const totalTitle = ref("");
const applyHistoryList = ref([]);

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },

  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList
  return ywApproveList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};


function paseTags(row) {
  let val = '';
  let color = '';
  switch (row.state) {
    case 'RUNNING':
      val = '审批中';
      color = 'orange';
      break;
    case 'PASSED':
      val = '已通过';
      color = 'green';

      break;
    case 'REJECTED':
      val = '已驳回';
      color = 'red';

      break;
    case 'CANCELED':
      val = '已撤销';
      break;
    default:
      break;
  }
  return { color, val }
}


function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}



//查看审批详情
function applyViewFn(record) {
  approvalHistory(record).then((res) => {
    if (res.code == 200) {
      for (let i = 0; i < res.data.length; i++) {
        let element = res.data[i];
        let color = "";
        if (element.nodeName == "流程结束") {
          if (res.data[i - 1].endTime) {
            color = "green";
          }
        } else {
          if (element.endTime) {
            color = "green";
          }
        }
        element.color = color;
      }

      applyHistoryList.value = res.data;
      applyViewOpen();
    } else {
      createMessage.error(res.message);

    }

  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });

}

function approveAbolishFn(record: Recordable) {
  //console.log(record);

  approveAbolish(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}

// const showTotalObj=ref(false);
function getCountDeptTotalLogFn(month) {
  let data = {};
  if (month) {
    data = { month };
  }
  getCountDeptTotalLog(data).then((res) => {
    if (res.code == 200) {
      // console.log(res.data);
      let obj = res.data.totalData;

      totalObj.value = obj ? obj : { salesmanDeptList: [] };
      let t = "部门抽成汇总";

      if (obj && obj.salesmanDeptList) {
        t += ":" + obj.salesmanDeptList.join("、");

      }
      totalTitle.value = t

      //  console.log("---totalObj.value:", totalObj.value);

    } else {
      createMessage.error(res.message);

    }

  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}

onMounted(() => {
  getCountDeptTotalLogFn(null);
})

function getActions(record) {
  let arr = [];
  let userName = userStore.getUserInfo?.userName;
  arr.push({
    // icon: 'clarity:note-edit-line',
    label: '查看',
    onClick: handleEdit.bind(null, record),
  });
  arr.push({
    // icon: 'clarity:note-edit-line',
    label: '查看审批详情',
    onClick: applyViewFn.bind(null, record),
  });
  if (record.state == "RUNNING") {

    arr.push({
      // icon: 'ant-design:delete-outlined',
      label: '撤回',
      color: 'error',
      popConfirm: {
        title: '是否撤回该申请？',
        placement: 'left',
        loading: record.loading,
        confirm: handleClose.bind(null, record),
      },
    });
  } else {
    if (userName == 'manage') {
      //   arr.push({
      //   // icon: 'ant-design:delete-outlined',
      //   label: '撤回',
      //   color: 'error',
      //   popConfirm: {
      //     title: '是否撤回该申请？',
      //     placement: 'left',
      //     confirm: handleClose.bind(null, record),
      //   },
      // });
    }
  }
  if (record.state == "REJECTED" && !record.stateName) {//已拒绝

    arr.push({
      // icon: 'ant-design:delete-outlined',
      label: '作废',
      color: 'error',
      popConfirm: {
        title: '作废后可前往抽成页面重新发起申请',
        placement: 'left',
        confirm: approveAbolishFn.bind(null, record),
      },
    });
  }
  if (record.state == "PASSED" && record.isSync == 0) {
    // arr.push({
    //   label: '同步',
    //   popConfirm: {
    //     title: '是否同步到数据采集表？',
    //     placement: 'left',
    //     confirm: handleSycnFn.bind(null, record),
    //   },
    // });
  }


  return arr;
}

function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record
  });
}

function monthChangeFn(e, r) {
  getCountDeptTotalLogFn(r);
}

function handleClose(record: Recordable) {
  //console.log(record);
  // loading.value = true;
  record.loading = true;
  approveBack(record)
    .then((res) => {
      record.loading = false;
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      record.loading = false;
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}


function handleSycnFn(record: Recordable) {
  //console.log(record);

  syncMoneyTable(record)
    .then((res) => {
      if (res.code == 200) {
        if (res.data) {
          createMessage.error(res.data[0].errorMessage);
          return;
        } else {
          createMessage.success(res.message);
          tableRef.value.commitProxy('reload');
        }


      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      // createMessage.error(res.message);
    })
    .finally(() => {
    });
}

function handleSuccess() {
  tableRef.value.commitProxy('reload');
}


function openUserModal(record: Recordable, type) {
  record.openType = type; // type 1 看符合退款条件的数据 2 看已有的数据
  orderModal[1].openModal(true, record);
}


</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}
</style>
